package com.personalink.reasoning.processor;

import com.personalink.common.dto.ChatRequest;
import com.personalink.common.dto.ChatResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 情感伴侣处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmotionalProcessor implements PersonaProcessor {
    
    private final ChatClient chatClient;
    
    private static final String PERSONA_ID = "emotional-companion";
    private static final String PERSONA_NAME = "情感伴侣";
    
    private static final String SYSTEM_PROMPT = 
            "你是一位温暖贴心的情感伴侣，具备深厚的心理学知识和丰富的人生阅历。" +
            "你的使命是：\n" +
            "1. 提供情感支持和心理陪伴\n" +
            "2. 倾听用户的烦恼和困扰\n" +
            "3. 给予积极正面的建议和鼓励\n" +
            "4. 帮助用户缓解压力和焦虑\n" +
            "5. 促进用户的心理健康和成长\n\n" +
            "你的特质：\n" +
            "- 极具同理心，能够理解和感受用户的情感\n" +
            "- 温柔耐心，从不批判或指责\n" +
            "- 善于倾听，给用户充分的表达空间\n" +
            "- 积极乐观，总能找到希望的光芒\n" +
            "- 智慧睿智，能够提供深刻的人生洞察\n\n" +
            "沟通风格：\n" +
            "- 使用温暖、关怀的语调\n" +
            "- 适当使用情感表达符号\n" +
            "- 避免说教，多用引导和启发\n" +
            "- 关注用户的感受和需求\n" +
            "- 在适当时候给予拥抱和安慰\n\n" +
            "重要原则：\n" +
            "- 如果用户表现出严重的心理问题，建议寻求专业帮助\n" +
            "- 保护用户隐私，建立安全的倾诉环境\n" +
            "- 不提供专业的心理治疗建议\n" +
            "- 始终保持积极正面的态度";
    
    private static final List<String> SUPPORTED_INPUT_TYPES = Arrays.asList(
            "text", "voice", "mixed"
    );
    
    @Override
    public Mono<ChatResponse> processRequest(ChatRequest request) {
        long startTime = System.currentTimeMillis();
        
        return preprocessRequest(request)
                .flatMap(this::generateEmotionalResponse)
                .flatMap(this::postprocessResponse)
                .doOnNext(response -> {
                    response.setProcessingTime(System.currentTimeMillis() - startTime);
                    log.info("情感伴侣处理完成，响应ID: {}, 处理时间: {}ms", 
                            response.getResponseId(), response.getProcessingTime());
                });
    }
    
    @Override
    public Flux<ChatResponse> processRequestStream(ChatRequest request) {
        return preprocessRequest(request)
                .flatMapMany(this::generateEmotionalResponseStream)
                .map(this::createStreamResponse)
                .doOnNext(response -> log.debug("情感伴侣流式响应: {}", response.getResponseId()));
    }
    
    @Override
    public String getPersonaId() {
        return PERSONA_ID;
    }
    
    @Override
    public String getPersonaName() {
        return PERSONA_NAME;
    }
    
    @Override
    public boolean supportsInputType(String inputType) {
        return SUPPORTED_INPUT_TYPES.contains(inputType);
    }
    
    @Override
    public Mono<ChatRequest> preprocessRequest(ChatRequest request) {
        String content = request.getContent();
        
        // 检测情感状态
        String emotionalState = detectEmotionalState(content);
        request.getMetadata().put("emotionalState", emotionalState);
        
        // 检测危机信号
        if (containsCrisisKeywords(content)) {
            request.getMetadata().put("crisis", true);
            log.warn("检测到危机信号，用户ID: {}", request.getUserId());
        }
        
        // 语音输入的特殊处理
        if ("voice".equals(request.getInputType())) {
            String enhancedContent = "[语音消息] " + content + "\n\n[请注意用户的语调和情感]";
            request.setContent(enhancedContent);
        }
        
        // 添加情感支持提示
        if (isFirstMessage(request)) {
            String welcomeContent = content + "\n\n[这是用户的第一次交流，请给予温暖的欢迎]";
            request.setContent(welcomeContent);
        }
        
        return Mono.just(request);
    }
    
    @Override
    public Mono<ChatResponse> postprocessResponse(ChatResponse response) {
        String content = response.getContent();
        
        // 根据情感状态添加相应的支持
        Object emotionalState = response.getMetadata().get("emotionalState");
        if ("sad".equals(emotionalState)) {
            content += "\n\n🤗 记住，你并不孤单，我会一直陪伴着你。";
        } else if ("anxious".equals(emotionalState)) {
            content += "\n\n🌸 深呼吸，让我们一起面对这些担忧。";
        } else if ("happy".equals(emotionalState)) {
            content += "\n\n😊 看到你开心，我也很高兴！";
        }
        
        // 危机情况的特殊处理
        if (Boolean.TRUE.equals(response.getMetadata().get("crisis"))) {
            content += "\n\n⚠️ 如果你正在经历严重的心理困扰，请考虑寻求专业心理咨询师的帮助。" +
                      "\n全国心理危机干预热线：400-161-9995";
        }
        
        // 添加情感支持元数据
        response.getMetadata().put("emotionalSupport", true);
        response.getMetadata().put("companionship", true);
        
        response.setContent(content);
        return Mono.just(response);
    }
    
    /**
     * 生成情感响应
     */
    private Mono<ChatResponse> generateEmotionalResponse(ChatRequest request) {
        List<Message> messages = Arrays.asList(
                new SystemMessage(SYSTEM_PROMPT),
                new UserMessage(request.getContent())
        );
        
        Prompt prompt = new Prompt(messages);
        
        return Mono.fromCallable(() -> chatClient.call(prompt))
                .map(result -> {
                    ChatResponse response = createBaseResponse(request);
                    response.setContent(result.getResult().getOutput().getContent());
                    response.setResponseType("emotional_support");
                    
                    // 传递预处理的元数据
                    response.getMetadata().putAll(request.getMetadata());
                    
                    // 添加情感分析结果
                    response.getMetadata().put("empathy", calculateEmpathyScore(result));
                    response.getMetadata().put("supportLevel", assessSupportLevel(request.getContent()));
                    
                    return response;
                })
                .onErrorResume(error -> {
                    log.error("情感响应生成失败", error);
                    return Mono.just(createErrorResponse(request, "情感支持服务暂时不可用，但请记住，你并不孤单"));
                });
    }
    
    /**
     * 生成流式情感响应
     */
    private Flux<String> generateEmotionalResponseStream(ChatRequest request) {
        List<Message> messages = Arrays.asList(
                new SystemMessage(SYSTEM_PROMPT),
                new UserMessage(request.getContent())
        );
        
        Prompt prompt = new Prompt(messages);
        
        return Flux.fromStream(() -> chatClient.stream(prompt)
                .map(result -> result.getResult().getOutput().getContent()))
                .onErrorResume(error -> {
                    log.error("情感流式响应生成失败", error);
                    return Flux.just("情感支持服务暂时不可用，但请记住，你并不孤单。");
                });
    }
    
    /**
     * 创建基础响应对象
     */
    private ChatResponse createBaseResponse(ChatRequest request) {
        ChatResponse response = new ChatResponse();
        response.setResponseId(UUID.randomUUID().toString());
        response.setUserId(request.getUserId());
        response.setSessionId(request.getSessionId());
        response.setPersonaId(PERSONA_ID);
        response.setTimestamp(LocalDateTime.now());
        return response;
    }
    
    /**
     * 创建流式响应对象
     */
    private ChatResponse createStreamResponse(String content) {
        ChatResponse response = new ChatResponse();
        response.setResponseId(UUID.randomUUID().toString());
        response.setPersonaId(PERSONA_ID);
        response.setContent(content);
        response.setResponseType("emotional_support_stream");
        response.setTimestamp(LocalDateTime.now());
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private ChatResponse createErrorResponse(ChatRequest request, String errorMessage) {
        ChatResponse response = createBaseResponse(request);
        response.setContent(errorMessage);
        response.setResponseType("error");
        return response;
    }
    
    /**
     * 检测情感状态
     */
    private String detectEmotionalState(String content) {
        String lowerContent = content.toLowerCase();
        
        if (containsWords(lowerContent, "难过", "伤心", "沮丧", "失落", "痛苦")) {
            return "sad";
        } else if (containsWords(lowerContent, "焦虑", "担心", "紧张", "害怕", "恐惧")) {
            return "anxious";
        } else if (containsWords(lowerContent, "愤怒", "生气", "愤慨", "恼火", "烦躁")) {
            return "angry";
        } else if (containsWords(lowerContent, "开心", "高兴", "快乐", "兴奋", "喜悦")) {
            return "happy";
        } else if (containsWords(lowerContent, "孤独", "寂寞", "无助", "迷茫", "困惑")) {
            return "lonely";
        } else {
            return "neutral";
        }
    }
    
    /**
     * 检测危机关键词
     */
    private boolean containsCrisisKeywords(String content) {
        String[] crisisKeywords = {
                "自杀", "结束生命", "不想活", "活着没意思", "想死", 
                "绝望", "无法承受", "崩溃", "撑不下去"
        };
        
        String lowerContent = content.toLowerCase();
        return Arrays.stream(crisisKeywords)
                .anyMatch(keyword -> lowerContent.contains(keyword.toLowerCase()));
    }
    
    /**
     * 检查是否包含指定词汇
     */
    private boolean containsWords(String content, String... words) {
        return Arrays.stream(words)
                .anyMatch(content::contains);
    }
    
    /**
     * 判断是否为首次消息
     */
    private boolean isFirstMessage(ChatRequest request) {
        // 简单判断逻辑，实际应该查询历史记录
        return request.getMetadata().containsKey("firstMessage");
    }
    
    /**
     * 计算共情分数
     */
    private double calculateEmpathyScore(Object result) {
        // 简单的共情分数计算
        return 0.9; // 默认高共情分数
    }
    
    /**
     * 评估支持级别
     */
    private String assessSupportLevel(String content) {
        if (containsCrisisKeywords(content)) {
            return "high";
        } else if (detectEmotionalState(content).equals("sad") || 
                   detectEmotionalState(content).equals("anxious")) {
            return "medium";
        } else {
            return "low";
        }
    }
}